package com.bitmain.mmst.miner.monitor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;

import com.bitmain.mmst.miner.monitor.executor.MinerCommandExecutor;
import com.bitmain.mmst.miner.monitor.executor.MinerCommandMessage;
import com.google.gson.JsonObject;
import com.xiamo.socket.MinerSocketDemo.Command;

/**
 * 
 *
 * @author Richard - rui.wu@bitmain.com
 * @since 2016年7月6日
 *
 */
public class MinerCommandDetector extends MinerMonitor{

	public void execute(){
		
		
		
		List<MinerCommandMessage> messages = new ArrayList<MinerCommandMessage>();
		messages = resolve(messages);
		ExecutorService service = Executors.newFixedThreadPool(3);
		for(MinerCommandMessage message:messages){
			submitExecutor(service,message);
		}
	}

	private void submitExecutor(ExecutorService service, MinerCommandMessage message) {
		MinerCommandExecutor executor = new MinerCommandExecutor(message,Command.ALL.key);
		CompletableFuture<MinerCommandMessage> future = CompletableFuture.supplyAsync(executor, service);
		future.thenAccept(m -> processMessage(m));
	}

	private void processMessage(MinerCommandMessage message) {
		//JsonParser parser = new JsonParser();
		//JsonElement element = parser.parse(message.getStats()).getAsJsonObject().get("STATS");
		//JsonArray array = element.getAsJsonArray();
		
		//JsonObject stats = array.get(0).getAsJsonObject();
		
		//System.out.println(stats.toString());
	}
	
	public static String getString(JsonObject jsonObject, String propName) {
		if (jsonObject == null) {
			return null;
		}
		if (StringUtils.isBlank(propName)) {
			return null;
		}
		try {
			return jsonObject.get(propName).getAsString();
		} catch (Exception e) {
			return null;
		}
	}

	private List<MinerCommandMessage> resolve(List<MinerCommandMessage> messages) {
		if(messages==null)
			messages = new ArrayList<MinerCommandMessage>();
		
		MinerCommandMessage message = new MinerCommandMessage();
		message.setPingable(true);
		message.setMacable(true);
		message.setMac("ABC");
		message.setHost("192.168.20.56");
		message.setPort(4028);
		message.setExecuteTime(123);
		messages.add(message);
		
		message = new MinerCommandMessage();
		message.setPingable(true);
		message.setMacable(true);
		message.setMac("ABC");
		message.setHost("192.168.20.58");
		message.setPort(4028);
		message.setExecuteTime(123);
		messages.add(message);
		
		message = new MinerCommandMessage();
		message.setPingable(true);
		message.setMacable(true);
		message.setMac("ABC");
		message.setHost("192.168.20.100");
		message.setPort(4028);
		message.setExecuteTime(123);
		messages.add(message);
		
		return messages;
	}
}
